package cn.neusoft.baibang.exception;

import cn.neusoft.baibang.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice // 全局统一异常注解 交给spring管理 ResponseBody+ControllerAdvice 方法返回值会封装为json
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
      log.info("发生系统异常，异常信息为："+e.getMessage());
      return JSONResult.error(GlobaExceptionEnum.SERVICE_ERROR);
    }

    @ExceptionHandler(GlobalException.class)
    public JSONResult globaExceptionHandler(GlobalException e){
        e.printStackTrace();
        log.info("发生系统异常，异常信息为："+e.getMessage());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException methodArgumentNotValidException){
        methodArgumentNotValidException.printStackTrace();
        log.info("发生系统异常，异常信息为："+methodArgumentNotValidException.getMessage());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("参数校验失败，失败原因为：");
        List<ObjectError> allErrors = methodArgumentNotValidException.getBindingResult().getAllErrors();
        allErrors.forEach(objectError -> stringBuilder.append(objectError.getDefaultMessage()).append("；"));
        return JSONResult.error(stringBuilder.toString());
    }
}
